import random
import threading
import time

import cv2
import numpy as np

# 保存图片的间隔时间
SAVE_INTERVAL = 30

# 开启多少路摄像头
CAM_NUM = 10

# 从TXT里第几个摄像头开始开启
START_CAM_INDEX = random.randint(0, 50)
# START_CAM_INDEX = 30



class myThread(threading.Thread):
    def __init__(self, name, rtsp_path, points):
        threading.Thread.__init__(self)
        self.name = name
        self.rtsp_path = rtsp_path
        self.points = points

    def run(self):
        print("开始线程：" + self.name)
        add_new_cam(self.rtsp_path, points, self.name)
        print("退出线程：" + self.name)


def add_new_cam(rtsp_path, points, name):
    print(rtsp_path)
    # 创建模型
    mog = cv2.createBackgroundSubtractorMOG2()  # 定义高斯混合模型对象 mog
    gmg = cv2.bgsegm.createBackgroundSubtractorGMG()
    knn = cv2.createBackgroundSubtractorKNN(detectShadows=False)

    # 绘制蒙版

    cap = cv2.VideoCapture(rtsp_path)
    ret, frame = cap.read()
    mask = np.zeros(frame.shape, np.uint8)

    for point in points:
        point[0] = point[0] * frame.shape[1]
        point[1] = point[1] * frame.shape[0]

    points = np.array(points)
    mask = cv2.fillPoly(mask, [points], (255, 255, 255))

    # 初始化计时器用于判断时间
    time_now = time.time()

    # cv2.imshow("mask", mask)
    print(name + "获取第一张成功")
    while 1:
        try:
            ret, frame = cap.read()
            frame_to_save = frame.copy()
            # frame_to_show = frame.copy()
            frame = cv2.bitwise_and(frame, mask)

            # 混合高斯模型
            fgmask = mog.apply(frame)  # 使用前面定义的高斯混合模型对象 mog 当前帧的运动目标检测，返回二值图像
            gray_frame = fgmask.copy()
            kernel = np.ones((5, 5), np.uint8)
            gray_frame = cv2.morphologyEx(gray_frame, cv2.MORPH_OPEN, kernel)
            # 返回值： contours，轮廓的坐标。 hierarchy，各个框之间父子关系，不常用。
            contours, hierarchy = cv2.findContours(gray_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            # 绘制每一个轮廓框到原始图像 frame 中
            for contour in contours:
                if cv2.contourArea(contour) < 1500:  # 计算候选框的面积，如果小于1500，跳过当前候选框
                    continue
                (x, y, w, h) = cv2.boundingRect(contour)  # 根据轮廓，得到当前最佳矩形框
                # cv2.rectangle(frame_to_show, (x, y), (x + w, y + h), (255, 255, 0), 2)  # 将该矩形框画在当前帧 frame 上

                # 根据时间间隔保存图片
                interval = time.time() - time_now

                if interval > SAVE_INTERVAL:
                    # 保存图片
                    print((x, y, w, h), name)
                    cv2.imwrite(filename="image/" + name + str(time_now) + ".jpg", img=frame_to_save)
                    time_now = time.time()

            # cv2.imshow("gray", gray_frame)
            # cv2.imshow("contours", frame_to_show)  # 显示当前帧
            # cv2.waitKey(1)
        except Exception as e:
            print(e)


# def get_rtsp_from_devicenum(devicenum):
#     url = "http://192.168.1.195:8080/cameraPicPoint/camera/" + devicenum
#
#     res = requests.get(url)
#     json_data = json.loads(res.text)
#     rtsp = json_data['data']['url']
#     return rtsp


# points为传入点的矩阵,[[x坐标/宽,y坐标/高]]
points = [[0, 0], [1, 0], [1, 1], [0, 1]]
list_name = []
list_num = []
list_rtsp = []
with open("双胞胎相机.txt", "r", encoding='utf-8') as f:
    devices = f.readlines()

for device in devices:
    device_info = device.split("	")
    name = device_info[1].replace("\n", "")
    list_name.append(name)
    list_num.append(device_info[0])

import requests
import json

for i in range(CAM_NUM):
    url = "http://192.168.1.195:8080/cameraPicPoint/camera/" + list_num[START_CAM_INDEX + i]

    res = requests.get(url)
    json_data = json.loads(res.text)
    rtsp = json_data['data']['url']
    list_rtsp.append(rtsp)

print(list_name)
print(list_rtsp)

for index in range(len(list_rtsp)):
    thread = myThread(list_num[START_CAM_INDEX + index], list_rtsp[index], points)
    thread.start()
    time.sleep(30)
